from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.filters import OrderingFilter  # 排序的过滤器
from rest_framework.response import Response
from django.conf import settings
from django_filters.rest_framework import DjangoFilterBackend

from luffyapi.libs.polyv import PolyvPlayer
from .models import CourseCategory, Course, CourseChapter
from .serializers import CourseCategoryModelSerializer, CourseModelSerializer, CourseRetrieveModelSerializer, \
    CourseChapterModelSerializer
from .paginations import CoursePageNumberPagination


class CourseCategoryListAPIView(ListAPIView):
    queryset = CourseCategory.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")
    serializer_class = CourseCategoryModelSerializer


class CourseListAPIView(ListAPIView):
    queryset = Course.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")
    serializer_class = CourseModelSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]  # 过滤器
    filter_fields = ("course_category",)  # 过滤条件
    ordering_fields = ("id", "student", "price")  # 排序的条件
    pagination_class = CoursePageNumberPagination


class CourseRetrieveAPIView(RetrieveAPIView):
    queryset = Course.objects.filter(is_show=True, is_deleted=False).order_by("orders", "-id")
    serializer_class = CourseRetrieveModelSerializer


class CourseChapterListAPIView(ListAPIView):
    queryset = CourseChapter.objects.filter(is_show=True, is_deleted=False).order_by("orders", "id")
    serializer_class = CourseChapterModelSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


class PolyvAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取视频播放的token"""
        userId = settings.POLYV_CONFIG["userId"]
        secretkey = settings.POLYV_CONFIG["secretkey"]
        tokenUrl = settings.POLYV_CONFIG["tokenUrl"]
        polyv = PolyvPlayer(userId, secretkey, tokenUrl)
        vid = request.query_params.get("vid")
        user_ip = request.META.get("REMOTE_ADDR")  # 用户的IP
        user_id = request.user.id  # 用户ID
        user_name = request.user.username  # 用户名

        result = polyv.get_video_token(vid, user_ip, user_id, user_name)
        return Response(result.get("token"))
